<template>
  <div class="editor-page">
    <!-- 编辑器 -->
    <AmisEditor id="editorName" :isMobile="mobileModel" :onChange="editorChanged" :preview="previewModel"
      :value="currentPageMenuItem.data" className="test-amis-editor" theme="cxd" />
    <div class="bottools">
      <!-- 当前编辑页面 -->
      <span class="current_page_info">当前编辑页面：{{ currentPageMenuItem.label }}&emsp;{{
        currentPageMenuItem.code
      }}</span>
      <!-- 保存 -->
      <el-button style="width:100px" type="success" @click="submit">保存</el-button>
      <!-- 预览 -->
      <el-button style="position: absolute;right: 140px" type="primary" @click="preview">页面预览</el-button>
      <!-- 返回主界面 -->
      <el-button style="position: absolute;right: 20px" type="warning" @click="backToMain">返回主界面</el-button>
    </div>
  </div>
  <!-- 返回弹窗 -->
  <message-box v-model:visible="backMessgeVisible" content-text="是否保存所编辑内容" title="确认返回？">
    <template #buttonGroup>
      <el-button @click="backMessgeVisible = false">继续编辑</el-button>
      <el-button type="danger" @click="handleBackToMain(1)">不保存并返回</el-button>
      <el-button type="primary" @click="handleBackToMain(2)">保存并返回</el-button>
    </template>
  </message-box>
</template>

<script lang="ts" setup>
import MessageBox from '@/components/MessageBox.vue'
// 引入一些样式依赖
import "amis-ui/lib/themes/default.css";
import "amis-ui/lib/themes/cxd.css";
import "amis-editor-core/lib/style.css";
import debounce from 'lodash/debounce';
import EditMenuDialog from "@/components/EditMenuDialog.vue";
import { applyReactInVue } from "veaury";
import { useRoute } from "vue-router";
import { Editor } from "amis-editor"; //引入编辑器

import { onMounted, ref, watch, } from "vue";
import router from "@/router";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import { portIsRunning } from '@/utils/commonFunction';
import { getMenuList, menuDetail, MenuInterface, updateMenu } from '@/api/menuManage';

const route = useRoute();
const AmisEditor = applyReactInVue(Editor); //使用编辑器


const previewModel = ref(false); //是否预览,实际开发中，如果需要编辑和预览，可以写一个change事件来改变这个值的状态
const mobileModel = ref(false); //是否是手机模式
//菜单树结构数据 
const backMessgeVisible = ref(false)

const isEditedCount = ref(0); //改变的次数

const hideComponents = ['pdf-viewer','office-viewer']//需要隐藏的组件

onMounted(() => {
  setPluginHide(hideComponents);
})

/**
* 设置插件隐藏
*
* 当页面加载完成后，自动隐藏所有包含data-dnd-data属性且属性值包含"form"的元素。
* 同时，使用MutationObserver监听DOM变化，以便在动态加载内容时也能及时隐藏符合条件的元素。
*/
function setPluginHide(hideList: String[]) {
  hideList.forEach((hideItem) => {

    // 查找所有包含data-dnd-data属性且属性值含"image"的元素
    const hideImageElements = () => {
      document.querySelectorAll('[data-dnd-data]').forEach((el: any) => {
        if (el) {
          const dataValue = el.getAttribute('data-dnd-data');
          if (dataValue && dataValue.includes(hideItem)) {
            el.style.display = 'none';
          }
        }
      });
    };

    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', hideImageElements);

    // 监听DOM变化（适用于动态加载内容）
    const observer = new MutationObserver(hideImageElements);
    observer.observe(document.body, {
      childList: true,
      subtree: true,
      attributes: true,
      attributeFilter: ['data-dnd-data']
    });
  })

}

function backToMain() {
  // 此处逻辑有待优化，如果编辑器内容没有改变,则isEditedCount值为1， 不弹出弹窗提示是否保存
  if (isEditedCount.value > 1) {
    backMessgeVisible.value = true
  } else {
    handleBackToMain(1)
  }
}

function submit() {
  updateMenu(currentPageMenuItem.value).then((res: any) => {
    ElMessage.success('保存成功')
    getMenuDetail()
    isEditedCount.value = 0
  })
}

/**
 * 根据不同类型处理返回主界面逻辑
 *
 * @param type 类型参数，1表示不保存直接返回主界面，2表示保存后返回主界面
 */
function handleBackToMain(type: number) {
  if (type == 1) {
    // 不保存当前编辑内容，直接返回主界面
    router.replace('/')
  }
  if (type == 2) {
    updateMenu(currentPageMenuItem.value).then((res: any) => {
      ElMessage.success('保存成功')
      router.replace('/')
    })
    // 保存当前编辑内容
  }
}


/**
 * 当编辑器内容发生变化时触发的函数。
 *
 * @param value - 编辑器当前的内容值。
 */
const editorChanged = (value: any) => {
  currentPageMenuItem.value.data = value;
  isEditedCount.value++;
};

/**
 * 跳转到预览页面
 */
async function preview() {
  updateMenu(currentPageMenuItem.value).then((res: any) => {
    isEditedCount.value = 0;
    router.push({ path: '/previewPage', query: { menuId: currentPageMenuItem.value.id, appId: appId } })
  })
}

const currentPageMenuItem = ref<MenuInterface>({} as MenuInterface);

const menuId = route.query.menuId as string;
const appId = route.query.appId as string;

function getMenuDetail() {
  menuDetail(menuId).then((res: any) => {
    let pageData = res.data.data
    if (pageData == null) {
      pageData = {}
    }
    let tObject = { ...res.data, data: pageData }
    currentPageMenuItem.value = tObject
  })
}

const dataSource = ref<MenuInterface[]>([])

function getAllMenuList() {
  getMenuList({ appId: appId }).then((res: any) => {
    dataSource.value = res.data.map((item: MenuInterface) => {
      return {
        ...item,
        disabled: item.type == '3' || item.type == '1'

      }
    })
  })
}

getMenuDetail()
getAllMenuList()
</script>


<style lang="scss" scoped>
@import '@/assets/style/iconfont.css';

el-loading-spinner .path {
  stroke: rgb(13, 161, 219);
}

:deep(.test-amis-editor) {
  height: 100% !important;
  overflow-y: auto;
  padding-bottom: 50px;
}

.bottools {
  padding: 5px;
  display: flex;
  justify-content: center;
  position: fixed;
  bottom: 0;
  width: 100%;
  background-color: #fff;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.12), 0 -2px 4px rgba(0, 0, 0, 0.04)
}

.previewbtn {
  background-color: #2468f2;
  padding: 10px;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
  text-align: center;

  &:hover {
    background-color: #1856d0;
  }
}

.current_page_info {
  line-height: 32px;
  position: absolute;
  left: 10px;
}

.editor-page {
  height: calc(100vh - 50px);
}
</style>